package com.example.demo.service;

import com.example.demo.mapper.*;
import com.example.demo.model.*;
import com.example.demo.tools.Constant;
import com.example.demo.tools.EncryptionTool;
import com.example.demo.tools.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WJ
 * Date: 2023-02-17
 * Time: 21:37
 */
@Service
public class OlderService {

    @Autowired
    private OlderMapper olderMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeeCommentMapper employeeCommentMapper;

    @Autowired
    private ActiveMapper activeMapper;

    @Autowired
    private EncryptionTool encryptionTool;        // 加密工具

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisUtil redisUtil;

//    获取所有的老人信息
    public Object getAllOlderDetailInfo(Integer id) {
        List<Older> olderList = olderMapper.getAllOlderDetailInfo(id);
        if(olderList != null){

            return olderList;
        }
        return "获取所有老人信息失败!";
    }


//    在老人管理中更新老人信息(前后台中都有使用)
    public Object updateOlderInfoInAdmin(Integer id,
                                         String address,
                                         Integer age,
                                         String clan,
                                         String clan_phone,
                                         Integer employee_id,
                                         String other_info,
                                         String phone,
                                         String sex,
                                         String username,
                                         String id_card,
                                         String photo_url,
                                         String password,
                                         String isLogin) {

        if(password != null && !"".equals(password)){
            password = encryptionTool.encrypt(password);
        }
        // 1.更新person中的信息
        Integer n1 = olderMapper.updateOlderInfoInPerson(id, username, sex, age, phone,photo_url,password);
        // 2.更新older_detail中的信息
        Integer n2 = olderMapper.updateOlderInfoInOlderDetail(id, id_card, address, clan, clan_phone, employee_id, other_info);
        // 3.更新employee_older中的信息
        if(employee_id != null){
            Integer n3 = employeeCommentMapper.updateEmployeeIdByOlderId(employee_id, id);
            if(n3 != 1){
                return "更新老人信息失败!";
            }
        }
        if(n1 == 1 && n2 == 1){
            if("重登".equals(isLogin)){
                // 删除session中的用户信息,让前台的用户重新登录
                redisUtil.deleteObject(Constant.USER_LOGIN+id);
            }
            return true;
        }
        return "更新失败!";
    }

//    删除老人
    public Object deleteOlderById(Integer id) {
        // 1. person中删除
        Integer n1 = olderMapper.deleteOlderInPerson(id);
        // 2. older_detail中删除
        Integer n2 = olderMapper.deleteOlderInOlderDetail(id);
        // 3. employee_older 中删除
        Integer n3 = employeeCommentMapper.deleteEmployeeOlderByOlderId(id);
        if(n1 == 1 && n2 == 1 && n3 == 1){
            return true;
        }
        return "删除老人信息失败!";
    }

//    获取所有的老人健康档案
    public Object getAllOlderHealthFiles() {
        List<HealthFiles> healthFiles = olderMapper.getAllOlderHealthFiles();
        if(healthFiles != null){
            return healthFiles;
        }
        return "查询老人健康档案失败!";
    }

//    通过healthId删除对应健康档案
    public Object deleteHealthFileById(Integer id) {
        Integer result = olderMapper.deleteHealthFile(id);
        if(result == 1){
            return true;
        }
        return "档案删除失败!";
    }

//    修改健康档案
    public Object updateHealthFileById(Integer id,
                                       Integer employee_id,
                                       Integer vaccination,
                                       Float temperature,
                                       Integer height,
                                       Float weight,
                                       Integer min_pressure,
                                       Integer respiratory_rate,
                                       Integer pulse,
                                       String electrocardiogram,
                                       Integer high_pressure) {

        Integer result = olderMapper.updateHealthFile
                (id, employee_id, vaccination, temperature, height, weight, min_pressure,
                        respiratory_rate, pulse, electrocardiogram, high_pressure);

        if(result == 1){
            return true;
        }
        return "修改健康档案失败!";
    }

//    根据条件查询老人信息（老人模块的查询,可以模糊查询）
    public Object getAllOlderInfoByUsernameOrAgeD(Integer id, String username, String phone, String id_card, Integer age) {
        List<Older> olderList = olderMapper.getAllOlderInfoOnAdminDown(id, username, phone, id_card, age);
        if(olderList != null){
            return olderList;
        }
        return "查询失败!";
    }

//    根据条件查询老人健康档案信息（档案模块的查询,可以模糊查询）
    public Object getAllOlderHealthInfoByMinPreOrMaxPre(Integer minMinPre, Integer minMaxPre, Integer maxMinPre, Integer maxMaxPre) {
        if(minMinPre != null && maxMinPre != null){
            // 低压 和 高压 都要查
            List<HealthFiles> list = olderMapper.getAllOlderHealthFilesBySelect(minMinPre, minMaxPre, maxMinPre, maxMaxPre);
            if(list != null){
                return list;
            }
        }else if(minMinPre != null){
            // 查低压
            List<HealthFiles> list = olderMapper.getAllOlderHealthFilesBySelect(minMinPre, minMaxPre, null, null);
            if(list != null){
                return list;
            }
        }else if(maxMinPre != null){
            // 查高压
            List<HealthFiles> list = olderMapper.getAllOlderHealthFilesBySelect(null, null, maxMinPre, maxMaxPre);
            if(list != null){
                return list;
            }
        }
        return "查询老人健康档案失败!";
    }

//    批量删除老人信息
    public Object deleteOneGroupOlderInfo(Integer[] oldersID) {
        for (Integer id:oldersID) {
            Integer n1 = olderMapper.deleteOlderInPerson(id);
            Integer n2 = olderMapper.deleteOlderInOlderDetail(id);
            Integer n3 = employeeCommentMapper.deleteEmployeeOlderByOlderId(id);
            if(n1 != 1 && n2 != 1 && n3 == 1){
                return "批量删除失败!";
            }
        }
        return true;
    }

//    批量删除老人健康档案信息
    public Object deleteOneGroupOlderHealthInfo(Integer[] oldersID) {
        for (Integer id:oldersID) {
            Integer n = olderMapper.deleteHealthFile(id);
            if(n != 1){
                return "批量删除失败!";
            }
        }
        return true;
    }

//    添加老人
    public Object addOlderInOlderManage(Older older, String photo_url, String other) {
        String encrypt = encryptionTool.encrypt("111111");
        older.setPassword(encrypt);
        if(photo_url == null || "".equals(photo_url)){
            // 默认图像
            older.setPhoto_url("https://pension-system-wj.oss-cn-beijing.aliyuncs.com/images/older.jpg");
        }else{
            older.setPhoto_url(photo_url);
        }
        if(other == null || "".equals(other)){
            older.setOther_info("暂时没有信息!");
        }else{
            older.setOther_info(other);
        }
        // 在person中添加
        Integer n1 = olderMapper.addOlderInfoInPerson(older);
        if(n1 == 1){
            // 在older_detail中添加
            Integer n2 = olderMapper.addOlderInfoInOlderDetail(older);
            if(n2 == 1){
                // 在employee_older中添加
                Integer n3 = employeeCommentMapper.addEmployeeOlder(older.getEmployee_id(), older.getId());
                if(n3 == 1){
                    return true;
                }
            }
        }
        return "添加老人失败!";
    }

//    通过老人id获取所有的健康档案
    public Object getAllHealthFilesByOlderId(Integer id) {
        List<HealthFiles> healthFiles = olderMapper.getAllHealthByOlderId(id);
        if(healthFiles != null){
            if(healthFiles.size() == 0){
                return healthFiles;
            }else{
                List<LoginUser> users = employeeMapper.getEmployeeList(healthFiles.get(0).getOlder_employee_id());
                if(users != null && users.size() != 0){
                    for (HealthFiles health:healthFiles) {
                        health.setOlder_employee_name(users.get(0).getUsername());
                        // 查询每个创建档案的人的名字
                        List<LoginUser> employeeList = employeeMapper.getEmployeeList(health.getEmployee_id());
                        if(employeeList == null || employeeList.size() == 0){
                            return "查询老人健康档案失败!";
                        }
                        health.setEmployee_name(employeeList.get(0).getUsername());
                    }
                    return healthFiles;
                }
            }
        }
        return "查询老人健康档案失败!";
    }

//    通过老人id获取该老人的详细信息
    public Object getInfoByOlderId(Integer id) {
        Older older = olderMapper.getOlderAllInfo(id);
        if(older != null){
            return older;
        }
        return "获取用户信息失败了!";
    }

//    通过老人id获取老人报名的活动信息
    public Object getAllActiveByOlderId(Integer id) {
        List<Active> activeList = olderMapper.getAllActiveIdByOlderId(id);
        if(activeList != null){
            for (Active active:activeList) {
                Employee employee = employeeMapper.getDetailInfoByEmployeeId(active.getActive_employee());
                if(employee != null){
                    active.setActive_employee_name(employee.getUsername());
                }else{
                    return "获取对应员工姓名失败!";
                }
            }
            return activeList;
        }
        return "获取老人所报名的活动信息失败!";
    }

//    检查是否评价过该员工
    public Object checkIsAppraise(Integer employeeId, Integer olderId) {
        Grade grade = employeeCommentMapper.getGradeByEmployeeIdAndOlderId(employeeId, olderId);
        // 不能评价
        if(grade == null){
            return 3;
        }
        // 可以评价
        if(grade.getIs_grade().equals("N")) {
            return 2;
        }
        // 已评价
        return 1;
    }

//    老人用户打分
    public Object commentGrade(Integer id, Float value, String txt, Integer older_id) {
        // 1. 先将这些数据存放到employee_older表中
        Integer n = employeeCommentMapper.updateEmployeeOlderByItems(id, value, txt, older_id);
        if(n == 1){
            // 具体的评价逻辑
            // value<2.5 : 直接减 0.5
            // value>2.5 && value < 3.5 : 直接减 0.2
            // value > 3.5 : 不变
            float grade = 0.0f;
            if(value < 2.5){
                // 获取 id 对应的员工分数
                Employee employee = employeeMapper.getEmployeeGrade(id);
                if(employee.getGrade() - 0.5f >= 0){
                    grade = employee.getGrade() - 0.5f;
                }
            }else if(value > 2.5 && value < 3.5){
                // 获取 id 对应的员工分数
                Employee employee = employeeMapper.getEmployeeGrade(id);
                if(employee.getGrade() - 0.2f >= 0){
                    grade = employee.getGrade() - 0.2f;
                }
            }else{
                return true;
            }

            // 新的得分存放进去
            Integer result = employeeMapper.updateEmployeeGradeByEmployeeIdForGrade(id, grade);
            if(result != null){
                return true;
            }
        }
        return "打分失败!";
    }

//    前台页面查询活动信息(根据条件可以模糊查询)
    public Object getActiveByItems(Integer active_id, String active_name, String active_address, String[] date) {
        String startTime = "";
        String endTime = "";

        if(date != null && date.length == 2){
            // 表示有时间范围
            startTime = date[0];
            endTime = date[1];
            try {
                    Calendar calendar = new GregorianCalendar();
                    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    // 给start_time加一天
                    Date dateStart = inputFormat.parse(startTime);
                    calendar.setTime(dateStart);
                    calendar.add(Calendar.DATE, 1);
                    dateStart = calendar.getTime();
                    startTime = outputFormat.format(dateStart);

                    // 给end_time加一天
                    Date dateEnd = inputFormat.parse(endTime);
                    calendar.setTime(dateEnd);
                    calendar.add(Calendar.DATE, 1);
                    dateEnd = calendar.getTime();
                    endTime = outputFormat.format(dateEnd);

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        List<Active> activeList = activeMapper.getActivesByUserItems(active_id, active_name, active_address, startTime, endTime);

        if(activeList != null){
            for (Active active:activeList) {
                List<LoginUser> result = employeeMapper.getEmployeeList(active.getActive_employee());
                active.setActive_employee_name(result.get(0).getUsername());
            }
            return activeList;
        }
        return "查询活动信息失败!";
    }


//    老人报名参加活动
    public Object joinActiveForOlder(Integer active_id, String active_name, Integer older_id, String older_name) {
        Integer n = olderMapper.addJoinActiveForOlder(active_id, active_name, older_id, older_name);
        if(n == 1){
            return true;
        }
        return "报名活动失败了!";
    }

//    添加老人健康档案
    public Object addOlderHealthFileInfo(Integer older_id,
                                         Float temperature,
                                         Integer height,
                                         Float weight,
                                         Integer respiratory_rate,
                                         Integer pulse,
                                         Integer min_pressure,
                                         Integer high_pressure,
                                         String electrocardiogram,
                                         Integer vaccination,
                                         Integer employee_id) {

        Integer n = olderMapper.addOlderHealthFileInfo(older_id, temperature,
                height, weight, respiratory_rate, pulse, min_pressure, high_pressure,
                electrocardiogram, vaccination, employee_id);

        if(n == 1){
            return true;
        }
        return "添加档案失败!";
    }

//    获取老人表明活动的信息列表
    public Object getJoinActiveOnOlder(Integer id) {
        List<OlderJoinInfo> joinInfos = activeMapper.getAllJoinInfoOnOlder(id);
        if(joinInfos != null){
            return joinInfos;
        }
        return "查询老人报名信息失败!";
    }

//    通过活动id获取所有的评论信息
    public Object getAllCommentByActiveId(Integer id) {
        List<Comment> commentList = activeMapper.getAllCommentByActiveId(id);

        if(commentList != null){
            for (Comment comment:commentList) {
                List<LoginUser> user = adminMapper.getAllCommentPersonInfo(comment.getComment_id());
                if(user == null || user.size() == 0){
                    return "查询评论人信息失败!";
                }
                comment.setComment_name(user.get(0).getUsername());
                comment.setComment_photo(user.get(0).getPhoto_url());
                comment.setStatus(user.get(0).getStatus());
            }
            return commentList;
        }
        return "查询评论信息失败!";
    }
}